package so.wy.servicecenter.businessbed.manager.inner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import so.wy.servicecenter.base.exception.ManagerException;
import so.wy.servicecenter.base.frame.manager.AbstractManager;
import so.wy.servicecenter.businessbed.dao.enums.StatusUserDepositEnum;
import so.wy.servicecenter.businessbed.dao.rdb.order.order.OrderDO;
import so.wy.servicecenter.businessbed.dao.rdb.rent_user.RentUserDO;
import so.wy.servicecenter.businessbed.manager.fm.OrderFManager;
import so.wy.servicecenter.businessbed.manager.fm.RentUserFManager;

import java.util.List;

@Service
@Scope("prototype")
public class RentUserIManager extends AbstractManager {

    @Autowired
    private RentUserFManager rentUserFManager;

    @Autowired
    private OrderFManager orderFManager;

    //判断租户是否可以下单并返回租户信息
    public RentUserDO checkCanOrder(Long userId) throws ManagerException {
        RentUserDO rentUserDO = checkRentUserExist(userId);

        //检验是否已支付押金
        if (StatusUserDepositEnum.NOTPAYD.getCode().equals(rentUserDO.getDepositStatus())){
            throw exception("未充值押金");
        }

        //检验是否还有正在进行中的订单
        OrderDO runOrder = orderFManager.getRentUserRunOrder(rentUserDO.getRentUserId());
        if (runOrder!=null){
            throw exception("请结束正在进行中的订单后进行租赁");
        }

        return rentUserDO;
    }

    //检验租户是否可以退还押金
    public void checkRentUserWithDraw(Long rentUserId) throws ManagerException {
        RentUserDO rentUserDO = getRentUserById(rentUserId);

        //检验是否已支付押金
        if (StatusUserDepositEnum.NOTPAYD.getCode().equals(rentUserDO.getDepositStatus())){
            throw exception("未充值押金");
        }

        // 校验租户是否有未支付的订单
        List<OrderDO> notPayOrder = orderFManager.getRentUserNotPayOrder(rentUserDO.getRentUserId());
        if (notPayOrder!=null&&notPayOrder.size()>0){
            throw exception("请支付未支付的订单后进行退款");
        }

    }

    public RentUserDO getRentUserById(Long rentUserId){
        return rentUserFManager.getRentUserById(rentUserId);
    }

    //校验用户对应租户是否存在
    public RentUserDO checkRentUserExistById(Long rentUserId) throws ManagerException {
        RentUserDO rentUserDO = rentUserFManager.getRentUserById(rentUserId);

        if (rentUserDO == null){
            throw exception("租户不存在");
        }

        return rentUserDO;
    }

    //校验用户对应租户是否存在
    public RentUserDO checkRentUserExist(Long userId) throws ManagerException {
        RentUserDO rentUserDO = rentUserFManager.getRentUser(userId);

        if (rentUserDO == null){
            throw exception("租户不存在");
        }

        return rentUserDO;
    }
}
